package com.zysdev.openglbeautydemo.filter.addFilter

import android.content.Context
import android.graphics.Bitmap
import android.opengl.GLES20
import android.opengl.GLUtils
import com.zysdev.openglbeautydemo.R
import com.zysdev.openglbeautydemo.filter.BaseFBOFilter
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.nio.FloatBuffer

class GiftFilter : BaseFBOFilter {
    private var scalePercent = 0
    private var scale = 0.0f //缩放，越大就放的越大，到2倍终止

    //出窍速度，越大则越快
    private val speed = 0.05f

    private var bitmapCoord = 0
    private var bitmapTexture = 0

    private var bitmap: Bitmap? = null

    // 纹理坐标缓冲区
    private var bitmapTextureBuffer: FloatBuffer? = null

    //    //GPU中的四个角的世界坐标 ,中心点位0,0
//    private var VERTEX = floatArrayOf(
//        -1.0f, -1.0f,
//        1.0f, -1.0f,
//        -1.0f, 1.0f,
//        1.0f, 1.0f
//    )
//    private var BITMAPTEXTURE = floatArrayOf(
//        0.2f, 0.4f,
//        0.4f, 0.4f,
//        0.2f, 0.2f,
//        0.4f, 0.2f
//    )

    constructor(context: Context, bitmap: Bitmap) : super(
        context,
        R.raw.base_vert,
        R.raw.base_frag
    ) {
        this.bitmap = bitmap;
        //得到变量句柄
        scalePercent = GLES20.glGetUniformLocation(program, "scalePercent")
//        mixturePercent = GLES20.glGetUniformLocation(program, "mixturePercent")

//        bitmapTextureBuffer =
//            ByteBuffer.allocateDirect(4 * 4 * 2).order(ByteOrder.nativeOrder()).asFloatBuffer()
//        bitmapTextureBuffer?.clear()
//        bitmapTextureBuffer?.put(BITMAPTEXTURE)
//
//        bitmapCoord = GLES20.glGetAttribLocation(program, "vBitmapCoord")
//        bitmapTexture = GLES20.glGetAttribLocation(program, "bitmapTexture")
    }

    override fun beforeBindTextureBuffer() {

//        bitmapTextureBuffer!!.position(0)
//        GLES20.glVertexAttribPointer(bitmapCoord, 2, GLES20.GL_FLOAT, false, 0, bitmapTextureBuffer)
//        //生效
//        GLES20.glEnableVertexAttribArray(bitmapCoord)


    }

    override fun beforeDraw() {
        super.beforeDraw()
        //使用变量句柄，给变量复制
        GLES20.glUniform1f(scalePercent, scale + 1.0f)
        /**
         *中间这里是你绘制的预览画面
         */
        //画水印（非动态）
        GLES20.glViewport(20, 20, 120, 120);

        GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);
//        bitmap!!.recycle()

        scale += speed
        if (scale >= 1.0) {
            scale = 0.0f
        }

    }


}